using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;

namespace Caramel.EntityFramework
{
	public class EntityFrameworkUnitOfWork : IUnitOfWork, IEntityFrameworkUnitOfWork
	{
		private bool _isDisposed = false;

		public EntityFrameworkUnitOfWork(DbContext context, string name)
		{
			this.Context = context;
			this.Name = name;
			this.ID = Guid.NewGuid();
		}

		#region IEntityFrameworkUnitOfWork Members

		public DbContext Context { get; private set; }

		#endregion

		#region IUnitOfWork Members

		public string Name { get; private set; }

		public Guid ID { get; private set; }

		public bool WasCommitted { get; private set; }

		public bool WasRolledBack { get; private set; }

		public void Commit()
		{
			try
			{
				this.Context.SaveChanges();
			}
			catch (System.Data.Entity.Validation.DbEntityValidationException e)
			{
				throw e;
			}
		}

		public void Rollback()
		{
		}

		public void Evict(object entity)
		{
			//this.Context.Entry(entity).State = System.Data.EntityState.Unchanged;
		}

		#endregion

		#region IDisposable Members

		public void Dispose()
		{
			if (!_isDisposed)
			{
				//if (_transaction.IsActive)
				//{
				//    this.Rollback();
				//}

				//_transaction = null;
				//this.Session.Dispose();
				//this.Session = null;

				UnitOfWork.DisposeOfUnitOfWork(this);

				_isDisposed = true;
			}
		}

		#endregion
	}
}
